/**
 * Copyright (c) <2010>, <SUNNY GUPTA>
 * All rights reserved.

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <ORGANIZATION> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <SUNNY GUPTA> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.gwtp.investmentadvisor.client.common;

import java.util.Collections;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.SuggestOracle;

/**
 * This implementation of {@link SuggestOracle} obtains suggestions from a server
 * It takes into account the following: -
 * 1. A small delay after the search Text changes to avoid too frequent updates. Also, search doesn't
 * happens until searchText > a minimum length
 * 2. It doesn't have any intelligence as to optimize requests. This is left with the presenter, which
 * can maintain a History of requests and accordingly choose to optimize server requests
 * 3. It DOES NOT make server calls directly, but rather invokes an event when it needs to fetch
 * data from server 
 * @author Sunny Gupta
 */
public class ServerQuerySuggestOracle extends SuggestOracle {
  public static int MIN_SEARCH_TEXT_LENGTH = 3;
  public static int SEARCH_TIMER_PERIOD = 500;

  /**
   * Callback interface for server.
   * @author Sunny Gupta
   */
  public interface ServerQueryCallback {
    void onServerResponseReady(Request request, Response response);
  }

  /**
   * Interface that server implementation will implement (The presenter).
   * @author Sunny Gupta
   */
  public interface SearchServer {
    void performServerQuery(Request request, ServerQueryCallback serverCallback);
  }

  /**
   * Timed search related fields.
   */
  private Timer searchTimer;
  private int minSearchTextLength;
  private int searchTimerPeriod;

  // Default Suggestion
  private Response defaultResponse = new Response(Collections.<Suggestion>emptyList());

  // Maintain request & callback
  private Request request;
  private Callback callback;

  // Search Server
  private SearchServer searchServer;

  public void configureSearchServer(SearchServer searchServer) {
    this.searchServer = searchServer;
  }

  // Server callback
  private final ServerQueryCallback serverCallback = new ServerQueryCallback() {
    @Override
    public void onServerResponseReady(Request request, Response response) {
      // Return response
      callback.onSuggestionsReady(request, response);
    }
  };

  public ServerQuerySuggestOracle() {
    // Initialize timer
    setMinSearchTextLength(MIN_SEARCH_TEXT_LENGTH);
    setSearchTimerPeriod(SEARCH_TIMER_PERIOD);
    this.searchTimer = new Timer() {
      /**
       * Handler for timer expiration event
       * When timer expires, the search is initiated
       */
      @Override
      public void run() {
      // Do the search
        doSearch();
      }
    };

    // Search Server
    this.searchServer = null;
  }

/**
 * Decides whether a Server Query is needed.
 */
  private void doSearch() {
    // Once again, check for minimum length since Request could have changed during timer run
    if (this.request.getQuery().length() >= this.minSearchTextLength) {
      // Request search
      this.searchServer.performServerQuery(this.request, this.serverCallback);
    } else {
      // Return default suggestion
      returnDefaultResponse();
    }
  }

  /* (non-Javadoc)
   * @see com.google.gwt.user.client.ui.SuggestOracle#requestSuggestions(com.google.gwt.user.client.ui.SuggestOracle.Request, com.google.gwt.user.client.ui.SuggestOracle.Callback)
   */
  @Override
  public void requestSuggestions(Request request, Callback callback) {
    /**
     * Any ongoing queries must be terminated as a new search is made on client
     * Associate request & callback
     */
    this.request = request;
    this.callback = callback;

    // Schedule search after delay time
    if (request.getQuery().length() >= this.minSearchTextLength) {
      // Cancel existing
      this.searchTimer.cancel();
      // Schedule timed search
      this.searchTimer.schedule(this.searchTimerPeriod);
    } else {
      // Return default suggestion
      returnDefaultResponse();
    }
  }

  /**
   * @param request 
   * @param callback
   */
  private void returnDefaultResponse() {
    this.callback.onSuggestionsReady(this.request, this.defaultResponse);
  }

  /**
   * @param minSearchTextLength the minSearchTextLength to set
   */
  public void setMinSearchTextLength(int minSearchTextLength) {
    this.minSearchTextLength = minSearchTextLength;
  }

  /**
   * @return the minSearchTextLength
   */
  public int getMinSearchTextLength() {
    return minSearchTextLength;
  }

  /**
   * @param searchTimerPeriod the searchTimerPeriod to set
   */
  public void setSearchTimerPeriod(int searchTimerPeriod) {
    this.searchTimerPeriod = searchTimerPeriod;
  }

  /**
   * @return the searchTimerPeriod
   */
  public int getSearchTimerPeriod() {
    return searchTimerPeriod;
  }

  /**
   * @param defaultResponse the defaultResponse to set
   */
  public void setDefaultResponse(Response defaultResponse) {
    this.defaultResponse = defaultResponse;
  }

  /**
   * @return the defaultResponse
   */
  public Response getDefaultResponse() {
    return defaultResponse;
  }
}
